package com.apobates.forum.core.impl.dao;

import com.apobates.forum.core.dao.TopicCarouselDao;
import com.apobates.forum.core.entity.TopicCarousel;
import java.util.Optional;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author xiaofanku
 * @see 20200614
 */
@Repository
public class TopicCarouselDaoImpl implements TopicCarouselDao{
    @PersistenceContext
    private EntityManager entityManager;
    private final static Logger logger = LoggerFactory.getLogger(TopicCarouselDaoImpl.class);
    
    @Override
    public Optional<TopicCarousel> findOne(String title) {
        TopicCarousel tc = null;
        
        try {
            tc = entityManager.createQuery("SELECT tc FROM TopicCarousel tc WHERE tc.title = ?1 AND tc.status = ?2", TopicCarousel.class)
                    .setParameter(1, title)
                    .setParameter(2, true)
                    .getSingleResult();
        } catch (javax.persistence.NoResultException e) {
            if(logger.isDebugEnabled()){
                logger.debug("通过标题查看轮播图失败", e);
            }
        }
        return Optional.ofNullable(tc);
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Optional<Boolean> editStatus(int id, boolean status) {
        int affect = entityManager.createQuery("UPDATE TopicCarousel tc SET tc.status = ?1 WHERE tc.id = ?2")
                .setParameter(1, status)
                .setParameter(2, id)
                .executeUpdate();
        return affect == 1 ? Optional.of(true) : Optional.empty();
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void save(TopicCarousel entity) {
        entityManager.persist(entity);
    }
    
    @Override
    public Optional<TopicCarousel> findOne(Integer primaryKey) {
        return Optional.ofNullable(entityManager.find(TopicCarousel.class, primaryKey));
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Optional<Boolean> edit(TopicCarousel updateEntity) {
        try {
            entityManager.merge(updateEntity);
            return Optional.of(true);
        } catch (Exception e) {
            if(logger.isDebugEnabled()){
                logger.debug("编辑轮播图失败", e);
            }
        }
        return Optional.empty();
    }
    
    @Override
    public Stream<TopicCarousel> findAll() {
        return entityManager.createQuery("SELECT tc FROM TopicCarousel tc", TopicCarousel.class).getResultStream();
    }
    
    @Override
    public long count() {
        return 0L;
    }
}